package com.android.Translator.Model;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import com.android.Translator.Model.utils.JsonReader;
import com.android.Translator.Model.utils.ParseJson;
import com.android.Translator.Presenter.TranslatorPresenter;
import com.example.entity.DataSearch;
import com.example.entity.DataTransalte;
import com.example.entity.Groups;
import com.example.entity.Words;
import com.example.provider.Provider;

public class TranslatorModel {
	// nhanvt add start
	// ConnectionDetector connectionN;
	// Boolean isInternetPresent = false;
	private DataTransalte translate;// = new DataTransalte();
	private static Provider db;
	private final static String TAG_MEAN = "tuc";
	private final static String TAG_EXAMPLE = "examples";
	private final static String TAG_PHRASE = "phrase";
	private final static String TAG_TEXT = "text";
	private final static String TAG_FIRST = "first";
	private final static String TAG_SECOND = "second";
	private final static String TAG_AUTHORS = "author";
	private Activity myActivity;

	public TranslatorModel(Activity activity) {
		// TODO Auto-generated constructor stub
		myActivity = activity;
		if (db==null)
			db = new Provider(myActivity.getApplicationContext());
		translate = new DataTransalte();
	}
	// nhanvt add end

	//[Quan] Ham cap nhat thuoc tinh isMine cua tu
	public void setIsMineForWord(Activity activity, String parse, String idGroup)
	{
		Words myword = db.getWord(parse);
		db.UpdateWords(activity, myword.getKeyword(), myword.getIdlang(),idGroup);
	}
	
	public String getGroup(String GroupName)
	{
		if (GroupName == null)
			return null;
		
		String idGroup = "";
		Groups group = db.getGroup(GroupName);
			if(group != null){
				idGroup = group.getIdGroup();
			}else{
					group = new Groups();
					group.setIdlang("0");
					group.setIdGroup(Calendar.getInstance().getTime()
							.toString());
					group.setGroupName(GroupName);
					group.setDateinsert(Calendar.getInstance().getTime()
							.toString());
					group.setDateupdate(Calendar.getInstance().getTime()
							.toString());
					group.setDatedelete(Calendar.getInstance().getTime()
							.toString());
					idGroup = db.createGroups(group);
					
					
			}
		return idGroup;
	}
	// [Quan] -- Ham nay duoc goi tu lop Presenter no thuc hien gui
	// request len API > Parse Json > ket qua se duoc tra ve sau khi
	// ASyncTask ket thuc tien trinh chay
	public void Translate(Activity activity, String parse, boolean isMyWord, String editGroup) {	
		// nhanvt edit start
		DataSearch dataSearch = new DataSearch();
		String groupID = getGroup(editGroup);
		if (parse != null && parse != "") {
			translate = db.translate(parse);
			if (translate != null) {
				//Quan -- cap nhat thuoc tinh isMine cua tu
				
					if (isMyWord &&  groupID != null)
					{
						setIsMineForWord(activity, parse,groupID);
						return;
					}
				//[Quan] -- end
				
				if (translate.getMean() != null || translate.getExam() != null) {
					try {

						ArrayList<String> lstMeans = new ArrayList<String>();
						ArrayList<String> lstExam = new ArrayList<String>();

						JSONObject jsonObjMean = new JSONObject(translate
								.getMean().getContent());
						JSONObject jsonObjExam = new JSONObject(translate
								.getExam().getContent());
						// Getting JSON Array node
						JSONArray mean = null;
						JSONArray exam = null;

						mean = jsonObjMean.getJSONArray(TAG_MEAN);
						exam = jsonObjExam.getJSONArray(TAG_EXAMPLE);
						// looping through All Contacts
						for (int i = 0; i < mean.length(); i++) {
							JSONObject c = mean.getJSONObject(i);
							if (c.has(TAG_PHRASE)) {
								String meaning = c.getString(TAG_PHRASE);
								JSONObject childObj = new JSONObject(meaning);
								String text = childObj.getString(TAG_TEXT);
								lstMeans.add(text);
							}
						}

						for (int i = 0; i < exam.length(); i++) {
							JSONObject c = exam.getJSONObject(i);
							String author = c.getString(TAG_AUTHORS);
							if (author.equals("31")) {
								String exampFirst = c.getString(TAG_FIRST);
								String exampSecond = c.getString(TAG_SECOND);
								lstExam.add(exampFirst);
								lstExam.add(exampSecond);
							}
						}
						dataSearch.setLstExam(lstExam);
						dataSearch.setLstMean(lstMeans);

					} catch (JSONException e) {
						e.printStackTrace();
					}
					TranslatorPresenter.setResultToListLocalView(dataSearch);
				}
			} else {
				final JsonReader reader = new JsonReader(activity,db, isMyWord?true:false, groupID);
				final ParseJson jsonParser = reader.getJsonParser();
				jsonParser.execute(parse);
			}
		}
		// nhanvt edit end
	}
	// end

	public ArrayList<String> getMyWords(String GroupName) {
		db = new Provider(myActivity.getApplicationContext());
		return db.getMyWord(GroupName);
	}

	public ArrayList<String> getGroupList() {
		// TODO Auto-generated method stub
		ArrayList<String> groupNameList = new ArrayList<String>();
		db = new Provider(myActivity.getApplicationContext());
		
		List<Groups> listGroup = db.getAllGroups();
		
		for (int i = 0; i< listGroup.size(); i++)
		{
			Log.i("Translator", "XXXXXX Group " + i +" :" + listGroup.get(i).getGroupName() );
			groupNameList.add(listGroup.get(i).getGroupName());
		}
		
		return groupNameList;
	}

	public void addGroup(String string) {
		// TODO Auto-generated method stub
		String groupID = getGroup(string);
		if (groupID != null)
			Toast.makeText(myActivity, "Add Successfull!", Toast.LENGTH_LONG).show();
		else
			Toast.makeText(myActivity, "Add Failure!", Toast.LENGTH_LONG).show();
	}
}
